package pers.lance.firstweb.servlet;

import pers.lance.firstweb.bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Base Servlet
 * override service method to filter the request
 */
@WebServlet(name = "UserInterceptServlet")
public class UserInterceptServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-Type", "text/html;charset=UTF-8");
        req.setCharacterEncoding("utf-8");

        HttpSession session = req.getSession();
        String servletPath = req.getServletPath();
        String status = (String) session.getAttribute("login_status");

        if (servletPath.equals("/login")) {
            super.service(req, resp);
        } else {
            if (status == null || !"logined".equals(status)) {
                if (servletPath.equals("/adduser")) {
                    User user = createUserFromReq(req);
                    session.setAttribute("usercache", user);
                }
                resp.sendRedirect("/login.html");
            } else {
                super.service(req, resp);
            }
        }
    }

    protected User createUserFromReq(HttpServletRequest req) {
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String birth = req.getParameter("birth");
        String major = req.getParameter("major");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
        Date date = null;
        try {
            date = simpleDateFormat.parse(birth);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new User(-1, name, password, date, major);
    }
}
